<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/departmenthead/DepartmentHeadAction.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Config.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class IndicatorValueEditAction extends DepartmentHeadAction {
	protected function execute(Response $response) {
		// определение года, для которого выполняется
		// просмотр целевых показателей
		if(isset($_POST['year'])) {
			$year = $_POST['year'];
		} elseif (isset($_SESSION['year'])) {
			$year = unserialize($_SESSION['year']);
		} else {
			$year = date("Y");
		}
		$_SESSION['year'] = serialize($year);

		// определение квартала, на который редактируются показатели
		if($year === date('Y')) {
			$quartes = Config::getQuarters($year);
			$quarte = null;
			$now = time();
			for($q = 4; $q >= 1; $q--) {
				if($now > $quartes[$q]) {
					$quarte = $q;
					break;
				}
			}
			$response->setParameter('quarte', $quarte);
		}

		// получение данных для соответствующих подразделений и календарного года
		$serviceFactory = new ServiceFactory();
		$service = $serviceFactory->getService('DepartmentService');
		$departments = $service->findByHead(unserialize($_SESSION['user']));
		$responsibilities = array();
		$indicatorValues = array();
		$service = $serviceFactory->getService('ResponsibilityService');
		$serviceIndicatorV = $serviceFactory->getService('IndicatorValueService');
		foreach($departments as $department) {
			$responsibility = $service->getByDepartmentAndYear($department->getIdentity(), $year);
			$responsibilities[$department->getIdentity()] = array();
			foreach($responsibility as $key => $value){
				if(!$value->isMonitoring()) {
					$responsibilities[$department->getIdentity()][] = $value;
					$indicatorValuesTemp = $serviceIndicatorV->getByResponsibility($value->getIdentity());
					$indicatorValues[$value->getIdentity()] = array();
					foreach ($indicatorValuesTemp as $indicatorValue) {
						$indicatorValues[$value->getIdentity()][$indicatorValue->getQuarter()] = $indicatorValue;
					}
				}
			}
			$responsibillities = array();
			foreach ($indicatorValues as $indicatorvalue){
				$indicatorvalue->setResponsibillity($service->read);
			}
		}
		
	
		
		
		
		$response->setParameter('departments', $departments);
		$response->setParameter('responsibilities', $responsibilities);
		$response->setParameter('indicatorValues', $indicatorValues);
		$response->setParameter('title', 'Редактирование целевых показателей');
		$response->setPagePath('/monitoring/index');
	}
}
?>